package gpar;

import gpar.ep.Candidate;
import gpar.io.Io;

import javax.tools.ToolProvider;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.DiagnosticCollector;

import java.net.URISyntaxException;
import java.net.URI;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

/** Allows a candidate to compile. Is still untested!!!
 * @author Maarten Inja */
public class Compiler
{
   
    private Program program;
 
    public Compiler(Program program)
    {
        this.program = program;
    }


    /** Returns a path to the compiled candidate, this is a .class file or
    * null when it can not be compiled. */
    public String compile(Candidate candidate) 
    {

        String compileReadyCode = candidate.toCodeString();

        // 1. Write to .java file
        String dotJavaFile = candidate.getClassName() + ".java"; // TODO: add path for the file
        File file = new File(dotJavaFile);
        Io.writeFile("outputBots/" + dotJavaFile, compileReadyCode, true);

        // 2. Options:
        String[] options = {"-d", "outputBots"}; 

        // 3. Compile:
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        DiagnosticCollector<JavaFileObject> diagnostics = 
            new DiagnosticCollector<JavaFileObject>();
        StandardJavaFileManager fileManager = 
            compiler.getStandardFileManager(diagnostics, null, null);
        Iterable<? extends JavaFileObject> compilationUnits = fileManager
            .getJavaFileObjectsFromStrings(Arrays.asList(file.getName()));
        JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, 
            diagnostics, Arrays.asList(options), // <- Iterable<String> options 
            null, compilationUnits);
        boolean success = task.call();
        
        try
        {
            fileManager.close();
        }
        catch (Exception e)
        {
            System.out.println("Error in gpar.Compiler.compile(Candidate candidate)");
            e.printStackTrace();
        } 

        System.out.println("Success: " + success);
        return "";
    }
}
